package com.youi.service.impl;

import com.youi.common.SessionKey;
import com.youi.dao.TremittanceDao;
import com.youi.entity.Groupleader;
import com.youi.entity.Sysuser;
import com.youi.entity.Tremittance;
import com.youi.entity.Userorderexcel;
import com.youi.manage.HttpSessionManage;
import com.youi.service.GroupleaderService;
import com.youi.service.SysuserService;
import com.youi.service.TremittanceService;
import com.youi.service.UserorderexcelService;
import com.youi.third.ali.oss.OSSUtil;
import com.youi.util.DateUtil;
import com.youi.util.FileUploadUtil;
import com.youi.util.ObjectUtil;
import com.youi.util.SmsUtil;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TremittanceServiceImpl extends BaseServiceImpl<Tremittance> implements TremittanceService {

    private TremittanceDao tremittanceDao;
    @Autowired
    private GroupleaderService groupleaderService;
    @Autowired
    private SysuserService sysuserService;
    @Autowired
    private UserorderexcelService userorderexcelService;

    @Autowired
    public void setfaultRecordDao(TremittanceDao tremittanceDao) {
        this.tremittanceDao = tremittanceDao;
        super.setBaseDAO(tremittanceDao);
    }

    @Override
    public void getTremittanceMsg(List<Tremittance> tremittanceList) {
        if (tremittanceList != null && tremittanceList.size() > 0) {
            for (Tremittance tremittance : tremittanceList) {
                getTremittanceMsg(tremittance);
            }
        }
    }

    @Override
    public void getTremittanceMsg(Tremittance tremittance) {
        if (tremittance != null) {
            //获取创建人名称
            if (tremittance.getType() == 2) {
                Groupleader groupleader = groupleaderService.get(tremittance.getCreatedUserId());
                if (groupleader != null) {
                    tremittance.setCreatedUserName(groupleader.getName());
                }
            } else {
                Sysuser creator = sysuserService.get(tremittance.getCreatedUserId());
                if (creator != null) {
                    tremittance.setCreatedUserName(creator.getName());
                }
            }
            //获取审核人名称
            Sysuser agreeUser = sysuserService.get(tremittance.getAgreeUserId());
            if (agreeUser != null) {
                tremittance.setAgreeUsername(agreeUser.getName());
            }
        }
    }

    @Override
    public void toExcelTremittance(HttpServletRequest request, List<Tremittance> tremittanceList) {
        try {
            Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
            String fileName = "tremittance" + new Date().getTime() + "" + SmsUtil.getRandom(3) + ".xls";//文件名
            String fileUrl = FileUploadUtil.getUploadUrl(request, "filedownload" + File.separator + fileName);//生成路径
            WritableWorkbook workbook = Workbook.createWorkbook(new File(fileUrl));
            WritableSheet sheet1 = workbook.createSheet("Sheet1", 0);
            WritableFont font = new WritableFont(WritableFont.createFont("微软雅黑"), 10);
            WritableCellFormat format = new WritableCellFormat();
            format.setAlignment(Alignment.CENTRE);
            format.setVerticalAlignment(VerticalAlignment.CENTRE);
            Label label = new Label(0, 0, "提现单号", format);
            sheet1.addCell(label);
            label = new Label(1, 0, "打款类型", format);
            sheet1.addCell(label);
            label = new Label(2, 0, "分润比例", format);
            sheet1.addCell(label);
            label = new Label(3, 0, "手续费", format);
            sheet1.addCell(label);
            label = new Label(4, 0, "订单总金额", format);
            sheet1.addCell(label);
            label = new Label(5, 0, "实际打款金额", format);
            sheet1.addCell(label);
            label = new Label(6, 0, "团长打款金额", format);
            sheet1.addCell(label);
            label = new Label(7, 0, "提现订单创建人", format);
            sheet1.addCell(label);
            label = new Label(8, 0, "收款方", format);
            sheet1.addCell(label);
            label = new Label(9, 0, "打款方式", format);
            sheet1.addCell(label);
            label = new Label(10, 0, "审核状态", format);
            sheet1.addCell(label);
            label = new Label(11, 0, "审核人", format);
            sheet1.addCell(label);
            label = new Label(12, 0, "审核时间", format);
            sheet1.addCell(label);
            label = new Label(13, 0, "打款时间", format);
            sheet1.addCell(label);
            label = new Label(14, 0, "创建时间", format);
            sheet1.addCell(label);
            Tremittance tremittance = null;
            for (int i = 0, j = 1; i < tremittanceList.size(); i++, j++) {
                tremittance = tremittanceList.get(i);
                ObjectUtil.ToChangeNullToEmpty(tremittance);
                label = new Label(0, j, tremittance.getWithdrawNo(), format);
                sheet1.addCell(label);
                label = new Label(1, j, ObjectUtil.getTremittanceType(tremittance.getType()), format);
                sheet1.addCell(label);
                label = new Label(2, j, String.valueOf(tremittance.getProfitRatio()), format);
                sheet1.addCell(label);
                label = new Label(3, j, String.valueOf(tremittance.getServiceCharge()), format);
                sheet1.addCell(label);
                label = new Label(4, j, String.valueOf(tremittance.getOrderAmount()), format);
                sheet1.addCell(label);
                String realityAmount = "0.00";
                if (tremittance.getRealityAmount() != null) {
                    realityAmount = tremittance.getRealityAmount().toString();
                }
                label = new Label(5, j, realityAmount, format);
                sheet1.addCell(label);
                label = new Label(6, j, "0.00", format);
                sheet1.addCell(label);
                label = new Label(7, j, tremittance.getCreatedUserName(), format);
                sheet1.addCell(label);
                label = new Label(8, j, tremittance.getPayeeName(), format);
                sheet1.addCell(label);
                label = new Label(9, j, "易宝分账", format);
                sheet1.addCell(label);
                label = new Label(10, j, ObjectUtil.getTremittanceStatus(tremittance.getStatus()), format);
                sheet1.addCell(label);
                label = new Label(11, j, tremittance.getAgreeUsername(), format);
                sheet1.addCell(label);
                if (tremittance.getGmtAgree() != null) {
                    label = new Label(12, j, DateUtil.simpdfyMdHms.format(tremittance.getGmtAgree()), format);
                    sheet1.addCell(label);
                }
                if (tremittance.getGmtReality() != null) {
                    label = new Label(13, j, DateUtil.simpdfyMdHms.format(tremittance.getGmtReality()), format);
                    sheet1.addCell(label);
                }
                label = new Label(14, j, DateUtil.simpdfyMdHms.format(tremittance.getGmtCreated()), format);
                sheet1.addCell(label);
            }
            workbook.write();
            workbook.close();
            InputStream inStream = new FileInputStream(fileUrl);
            byte[] data = ObjectUtil.readInputStream(inStream);
            String dowmupload = OSSUtil.upload(data, ".xls");
            if (dowmupload != null && dowmupload.length() > 0) {
                userorderexcelService.saveOrUpdate(new Userorderexcel(sysuser.getId(), 8, dowmupload));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (WriteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public Tremittance getForUpdate(Long id) {
        return tremittanceDao.getForUpdate(id);
    }

    @Override
    public List<Tremittance> listForFinishMerchantDivide(Long id) {
        return tremittanceDao.listForFinishMerchantDivide(id);
    }

    @Override
    public List<Map<String, Object>> merchantDivideStat(Long id) {
        return tremittanceDao.merchantDivideStat(id);
    }

    @Override
    public List<Tremittance> listForFinishPlatfotmDivide(Long id) {
        return tremittanceDao.listForFinishPlatfotmDivide(id);
    }

    @Override
    public List<Map<String, Object>> PlatfotmDivideStat(Long id) {
        return tremittanceDao.PlatfotmDivideStat(id);
    }

    @Override
    public List<Map<String, Object>> listRemittanceApplyByParam(Map<String, Object> param) {
        List<Map<String, Object>> list = tremittanceDao.listRemittanceApplyByParam(param);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        list.stream().forEach(remittance -> {
            Integer type = (Integer) remittance.get("type");
            remittance.put("typeTxt", ObjectUtil.getTremittanceType(type));

            Integer payType = (Integer) remittance.get("payType");
            if (payType != null) {
                if (payType == 0) {
                    remittance.put("payTypeTxt", "易宝分账");
                }
                if (payType == 1) {
                    remittance.put("payTypeTxt", "云享代付");
                }
            }
            remittance.put("statusTxt", ObjectUtil.getTremittanceStatus((Integer) remittance.get("status")));
            if (type != null && type == 2) {
                remittance.put("createdUserName", remittance.get("createdUserName2"));
            } else {
                remittance.put("createdUserName", remittance.get("createdUserName1"));
            }
            if (remittance.get("gmtAgree") != null) {
                try {
                    remittance.put("gmtAgree", DateUtil.simpdfyMdHms.format(DateUtil.simpdfyMdHms.parse(String.valueOf(remittance.get("gmtAgree")))));
                } catch (Exception e) {
                }
            }
            if (remittance.get("gmtReality") != null) {
                try {
                    remittance.put("gmtReality", DateUtil.simpdfyMdHms.format(DateUtil.simpdfyMdHms.parse(String.valueOf(remittance.get("gmtReality")))));
                } catch (Exception e) {
                }
            }
            if (remittance.get("gmtCreated") != null) {
                try {
                    remittance.put("gmtCreated", DateUtil.simpdfyMdHms.format(DateUtil.simpdfyMdHms.parse(String.valueOf(remittance.get("gmtCreated")))));
                } catch (Exception e) {
                }
            }
        });
        return list;
    }
}